<?php

namespace App\Http\Controllers;

use App\Models\ArticleCategory;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use \DB;
use App\Http\Requests\NewsTypeRequest;

class NewsTypeController extends CommonController
{
    /**
     * 获取分类列表
     *
     * @return Response
     */
    public function getList()
    {
        $lists = ArticleCategory::orderBy('id', 'asc')->paginate(10);

        return view('newstype.list')->with("lists", $lists)->with("actions", $this->actions);
    }

    /**
     * 显示分类编辑页面
     */
    public function getEdit(Request $request)
    {
        $id = $request->input('id');
        $list = ArticleCategory::where('id', '=', $id)->first();

        return view('newstype.edit')->with("list", $list);
    }

    /**
     * 编辑一个分类
     */
    public function postEdit(NewsTypeRequest $request)
    {
        $data = $request->input();
        unset($data['_token'], $data['formType']);
        $exists = ArticleCategory::where('name', $data['name'])->first();

        if (is_object($exists) && $exists->id != $data['id']) {
            return AjaxCallbackMessage('分类编辑失败，该名称已经存在', false);
        }

        $exists = ArticleCategory::where('code', $data['code'])->first();
        if (is_object($exists) && $exists->id != $data['id']) {
            return AjaxCallbackMessage('分类编辑失败，该code已经存在', false);
        }

        ArticleCategory::where('id', '=', $data['id'])->update($data);

        return AjaxCallbackMessage('分类编辑成功', true, url('newstype/list'));
    }

    /**
     * 显示分类创建页面
     */
    public function getCreate()
    {
        $lists = ArticleCategory::orderBy('id', 'asc')->get();

        return view('newstype.create')->with('lists', $lists);
    }

    /**
     * 创建一个分类
     */
    public function postCreate(NewsTypeRequest $request)
    {
        $data = $request->input();
        unset($data['_token'], $data['formType']);

        $result = ArticleCategory::create($data);

        if (is_object($result)) {
            return AjaxCallbackMessage('分类创建成功', true, url('newstype/list'));
        } else {
            return AjaxCallbackMessage('分类创建失败,未知错误', false);
        }
    }
}
